import { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { makePhoneCall, navigateTo, showToast } from '@tarojs/taro';
import { HouseEntity } from '@/entities/HouseEntity';
import houseStore from '@/stores/HouseStore';
import Navbar from '@/components/Navbar';
import HouseImageList from '@/components/HouseImageList';
import ShowCollectFees from '@/components/ShowCollectFees';
import ShowHouseMessage from '@/components/ShowHouseMessage';
import './index.less';
import { Image, Text, View } from '@tarojs/components';
import { LandlordEntity } from '@/entities/LandlordEntity';
import collectImg from '@/static/images/icon/collect.png';
import collectedImg from '@/static/images/icon/collected.png';
import PhoneImg from '@/static/images/icon/phone.png';
import ButtonComp from '@/components/Button';
import authStore from '@/stores/AuthStore';
import BusinessConstant from '@/constant/BusinessConstant';
import HouseLeaseBusiness from '@/business/HouseLeaseBusiness';
import AlterComp from '@/components/Alter';
import { HouseConstant } from '@/constant/HouseConstant';
import systemStore from '@/stores/SystemStore';
import useCollect from '@/hooks/useCollect';
import socketStore from '@/stores/SocketStore';
import AuthConstant from '@/constant/AuthConstant';
import arrowImg from '@/static/images/icon/arrow-right.png';
import ImageComp from '@/components/Image';
import ChatImg from '@/static/images/icon/chat.png';
import userStore from '@/stores/UserStore';
import chatStore from '@/stores/ChatStore';
import useChat from '@/hooks/useChat';
import Popup from '@/components/Popup';
import { Input } from '@nutui/nutui-react-taro';

const TenantLookHouse = () => {
  const { updateHouseCollectList, currentHouse } = houseStore;
  const { websocketInstance } = socketStore;
  const { user, currentLandlord } = userStore;
  const { setChatReceiver } = chatStore;
  const { changeCollectStatus, getHouseCollectStatus } = useCollect();
  const { useLeaveChatSession } = useChat();

  // 房屋信息
  const [houses, setHouses] = useState<HouseEntity.IResultHouse>();
  // 房东信息
  const [landlord, setLandlord] = useState<LandlordEntity.ILandlord>();
  // 已收藏
  const [collected, setCollected] = useState(false);
  // 租赁申请提示框
  const [leasePopupVisible, setLeasePopupVisible] = useState(false);
  // 租赁状态
  const [leaseState, setLeaseState] = useState(0);
  // 租赁信息popup
  const [leaseMsgVisible, setLeaseMsgVisible] = useState(false);
  const [leaseMonths, setLeaseMonths] = useState('');

  useLeaveChatSession();

  useEffect(() => {
    const houses: HouseEntity.IResultHouse = currentHouse;
    houses && setHouses(houses);

    const landlord: LandlordEntity.ILandlord = currentLandlord;
    landlord && setLandlord(landlord);

    return () => {
      houseStore.clearEditorCurrentHouse();
    };
  }, []);

  /**
   * 打电话
   */
  const phoneLandlord = () => {
    landlord?.phone &&
      makePhoneCall({
        phoneNumber: landlord.phone,
      });
  };

  /**
   * 去改变房屋的收藏状态
   */
  const toChangeHouseCollectStatus = async () => {
    const res: any = await changeCollectStatus(
      houses?.houseId!,
      landlord?.id!,
      Number(!collected)
    );
    setCollected(!collected);
    updateHouseCollectList(res.houseId, res.status);
  };

  /**
   * 获取当前房屋的收藏状态
   */
  const getCurrentHouseCollectStatus = async () => {
    if (houses?.houseId) {
      const status: number | null = await getHouseCollectStatus(houses.houseId);
      status && setCollected(Boolean(status));
    }
  };

  /**
   * 获取当前房屋的租赁状态
   */
  const getCurrentHouseLeaseStatue = async () => {
    // 未登录
    if (!authStore.isLogin) return;
    if (houses?.houseId && user?.id) {
      const res: any = await HouseLeaseBusiness.getLeaseStatus(
        houses?.houseId,
        user?.id
      );
      res?.status && setLeaseState(res.status);
    }
  };

  // 租客未登录进来，点击收藏或者租赁
  useEffect(() => {
    getCurrentHouseCollectStatus();
    getCurrentHouseLeaseStatue();
  }, [houses?.houseId, user?.id]);

  /**
   * 去租赁
   */
  const toLease = async () => {
    if (houses?.houseId && user?.id) {
      const res: any = await HouseLeaseBusiness.addLease({
        houseId: houses?.houseId,
        landlordId: landlord?.id!,
        tenantId: user?.id,
        leaseMonths: Number(leaseMonths),
      });
      if (!res.status) return;
      setLeaseState(res.status);
      showToast({
        title: '申请发送成功，等待处理！',
      });
      setLeasePopupVisible(false);
      websocketInstance &&
        websocketInstance.send({
          data: JSON.stringify({
            toIdentity: AuthConstant.LANDLORD,
            toId: landlord?.id!,
            active: BusinessConstant.SOCKET_GET_PENDING_LEASE,
          }),
        });
    }
  };

  /**
   * 处理点击租赁按钮事件
   */
  const handleClickLeaseBtn = () => {
    if (!authStore.isLogin) {
      navigateTo({
        url: `/pages/login/index?execute=${BusinessConstant.EXECUTE_BACK}`,
      });
      return;
    }
    setLeaseMsgVisible(true);
  };

  const lookHouseComment = () => {
    navigateTo({
      url: `/pages/houseAllComment/index?houseName=${houses?.name}&houseId=${houses?.houseId}`,
    });
  };

  const toChat = () => {
    setChatReceiver(currentLandlord);
    navigateTo({
      url: `/pages/chatMessage/index`,
    });
  };

  return (
    <Navbar mode='back' bgColor='var(--mini-third)' title={houses?.name}>
      <View
        className='tenant-look-container'
        style={{ height: systemStore.haveNavbarNotTabbarHeight }}
      >
        <HouseImageList imgList={JSON.parse(houses?.houseImg || '[]')} />
        <View className='contact-landlord-wrap'>
          <View className='landlord-info'>
            <View className='flex items-center'>
              <ImageComp
                src={landlord?.headImg}
                className='landlord-head-img'
              />
              <Text className='landlord-text'>{landlord?.name}</Text>
            </View>
            <View>
              <Image
                src={collected ? collectedImg : collectImg}
                className='icon'
                style={{ marginRight: '24px' }}
                onClick={toChangeHouseCollectStatus}
              />
              <Image
                src={PhoneImg}
                className='icon'
                onClick={phoneLandlord}
                style={{ marginRight: '20px' }}
              />
              <Image
                src={ChatImg}
                className='icon'
                mode='heightFix'
                style={{ width: '37px' }}
                onClick={() => toChat()}
              />
            </View>
          </View>
          <View className='comment-enter' onClick={lookHouseComment}>
            <Text>查看房屋评论</Text>
            <Image src={arrowImg} className='arrow-icon' />
          </View>
          {leaseState === HouseConstant.HouseToLeaseMap.rejected ||
          leaseState === HouseConstant.HouseToLeaseMap.rented ? (
            <ButtonComp
              title='租赁'
              className='lease-btn'
              bgColor='var(--mini-third)'
              onClick={handleClickLeaseBtn}
            />
          ) : (
            <View className='already-leased'>
              <View className='line'></View>
              <Text className='text'>已向房东发送租赁请求</Text>
              <View className='line'></View>
            </View>
          )}
        </View>
        <ShowCollectFees houses={houses} />
        <ShowHouseMessage houses={houses} />
        <AlterComp
          visible={leasePopupVisible}
          onClose={() => setLeasePopupVisible(false)}
          onConfirm={toLease}
          content='您的信息将会提供给房东，是否继续？'
        />
      </View>
      <Popup
        title='请填写租赁信息'
        visible={leaseMsgVisible}
        onClose={() => setLeaseMsgVisible(false)}
        onConfirm={async () => {
          if (!leaseMonths) {
            showToast({ title: '请填写租赁月数', icon: 'none' });
            return;
          }
          if (isNaN(Number(leaseMonths))) {
            showToast({ title: '租赁月数只能填数字', icon: 'none' });
            return;
          }
          setLeaseMsgVisible(false);
          setLeasePopupVisible(true);
        }}
      >
        <View className='flex items-center'>
          <Text>租赁月数：</Text>
          <Input
            placeholder='您打算租多少个月'
            onChange={(value) => setLeaseMonths(value)}
            type='number'
          ></Input>
        </View>
      </Popup>
    </Navbar>
  );
};

export default observer(TenantLookHouse);
